package com.tisco;
import com.domain.InitDomain;
import com.domain.ServerDomain;
import com.util.FileUtil;
import java.util.HashMap;
import java.util.List;

public class App {

    public static void main( String[] args ){
        if(args.length==1){
            String initFileName = args[0];
//            String initFileName = "F:/init8086.json";
            HashMap<String, Object> init = FileUtil.init(initFileName);
            Object obj = init.get("success");
            if(null != obj){
                final InitDomain initDomain = (InitDomain) obj;
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        System.out.println("启动Server");
                        TransferServer transferServer = new TransferServer(initDomain);
                        //提供Socket服务
                        transferServer.service();
                    }
                }).start();
    //            //Client端
                List<ServerDomain> serverDomainList = initDomain.getServerDomainList();
                for(int i=0;i<serverDomainList.size();i++){
                    final String ip = serverDomainList.get(i).getIp();
                    final Integer port = serverDomainList.get(i).getPort();
                    final String location = serverDomainList.get(i).getLocation();
                    final Integer reConnectCount = serverDomainList.get(i).getReConnectCount();
                    final Integer delay = serverDomainList.get(i).getDelay();
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            System.out.println("启动Client");
                            TransferClient transferClient = new TransferClient(ip, port);
                            boolean startFlag = (transferClient.socket==null);
                            for(int i=0;i<reConnectCount&&startFlag;i++){
                                System.out.println(delay + "秒之后，重新连接");
                                try {
                                    Thread.sleep(1000*delay);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                                transferClient = new TransferClient(ip, port);
                                startFlag = (transferClient.socket==null);
                            }
                            if(!startFlag){
                                System.out.println("连接成功");
                                transferClient.send(location);
                            }
                        }
                    }).start();

                }
            }else{
                System.out.println("初始化失败，请确认配置文件");
            }
        }else{
            System.out.println("初始化失败，请确认配置文件路径");
        }
    }

}
